﻿// =================================================================== 
// 项目说明
//====================================================================
// iMaker.Library@Copy Right 2010-2011
// 文件： FileOperate.cs
// 项目名称：公共类库，文件操作类
// 创建时间：2010-10-26
// 创建人：Jack
// 修改人：
// 修改说明：
// 修改时间：
// ===================================================================
using System;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;


namespace iMaker.Library
{
    public class FileOperate
    {
        public FileOperate()
        { }

        /// <summary>
        /// 检查上传文件的格式
        /// </summary>
        /// <param name="fileupload">上传文件控件</param>
        /// <param name="filetype">支持的文件格式</param>
        /// <returns></returns>
        public static bool CheckFileFormat(FileUpload fileupload, string[] filetype)
        {
            bool returnBool = false;
            try
            {
                string extension = Path.GetExtension(fileupload.PostedFile.FileName).Replace(".", "");

                if (filetype.Length != 0)
                {
                    foreach (string tempStr in filetype)
                    {
                        if (extension.ToLower() == tempStr.ToLower())
                        {
                            returnBool = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fileupload.Dispose();
            }
            return returnBool;
        }


        /// <summary>
        /// 文件上传方法,调用此方法前线做判断是否有选中文件  FIleUpload.HasFile
        /// </summary>
        /// <param name="fileupload">FileUpload控件名</param>
        /// <param name="filename">上传后的文件名</param>
        /// <param name="filepath">上传路径;Server.MapPath("") </param>
        /// <param name="filetype">可以上传的文件类型</param>
        /// <param name="maxfilelength">上传文件最大大小（0为可以上传任何大小），单位为字节</param>
        /// <param name="type">上传后文件的类型</param>
        /// <returns></returns>
        public static bool UploadFile(FileUpload fileupload, string filename, string filepath, string[] filetype, int maxfilelength, out string type)
        {
            bool returnBool = false;
            try
            {
                filename = filename.Replace("/", "").Replace("\\", "");
                string name = fileupload.FileName;//文件名字
                int size = fileupload.PostedFile.ContentLength;//文件大小
                type = fileupload.PostedFile.ContentType;//文件类型

                string itype = System.IO.Path.GetExtension(name).ToLower().Replace(".", "");//文件扩展名
                string ipath = filepath + filename + "." + itype;//上传后的路径
                type = itype;

                bool tempBool = false;

                //循环比较上传文件类型是否在文件类型数组内
                if (filetype.Length != 0)
                {
                    foreach (string tempStr in filetype)
                    {
                        if (itype == tempStr.ToLower())
                        {
                            tempBool = true;
                            break;
                        }
                    }
                }
                else
                    tempBool = true;

                //判断文件是否超出最大大小
                if (tempBool)
                {
                    if (maxfilelength != 0)
                        if (size > maxfilelength)
                            tempBool = false;
                }

                if (tempBool)
                {
                    fileupload.SaveAs(ipath);
                    returnBool = true;
                }

                fileupload.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnBool;
        }
        /// <summary>
        /// 保留原文件名
        /// </summary>
        /// <param name="fileupload">上传控件</param>
        /// <param name="filepath">上传路径</param>
        /// <param name="filetype">上传文件类型数组</param>
        /// <param name="maxfilelength">限制大小</param>
        /// <returns></returns>
        public static bool UploadFile(FileUpload fileupload,  string filepath, string[] filetype, int maxfilelength)
        {
            bool returnBool = false;
            try
            {
                string name = fileupload.FileName;//文件名字
                int size = fileupload.PostedFile.ContentLength;//文件大小
                string type = fileupload.PostedFile.ContentType;//文件类型

                string itype = System.IO.Path.GetExtension(name).ToLower().Replace(".", "");//文件扩展名
                string ipath = filepath+name  ;//上传后的路径
                type = itype;

                bool tempBool = false;

                //循环比较上传文件类型是否在文件类型数组内
                if (filetype.Length != 0)
                {
                    foreach (string tempStr in filetype)
                    {
                        if (itype == tempStr.ToLower())
                        {
                            tempBool = true;
                            break;
                        }
                    }
                }
                else
                {
                    tempBool = true;
                }

                //判断文件是否超出最大大小
                if (tempBool)
                    if (maxfilelength != 0)
                        if (size > maxfilelength)
                            tempBool = false;

                if (tempBool)
                {
                    fileupload.SaveAs(ipath);
                    returnBool = true;
                }

                fileupload.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnBool;
        }
        /// <summary>
        /// 缩放图片
        /// </summary>
        /// <param name="filePath">原图片路径 Server.MapPath("") </param>
        /// <param name="savePath">缩放后图片的路径 Server.MapPath("") </param>
        /// <param name="newWidth">缩放后图片的宽度，如果缩放方式不需要指定宽度，参数不会被使用</param>
        /// <param name="newHeight">缩放后图片的高度，如果缩放方式不需要指定高度，参数不会被使用</param>
        /// <param name="mode">缩放方式：1."HW" 指定高宽缩放（可能变形）;2."W" //指定宽，高按比例;3."H"://指定高，宽按比例;4."Cut"://指定高宽裁减（不变形） </param>
        public static void ResizeImage(string filePath, string savePath, int newWidth, int newHeight, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(filePath);
            
            int towidth = newWidth;//缩放后的宽度
            int toheight = newHeight;//缩放后的高度

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形） 
                    break;
                case "W"://指定宽，高按比例 
                    toheight = originalImage.Height * newWidth / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * newHeight / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * newHeight / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "MaxHWCut"://最大宽高缩放
                    towidth = newWidth > newHeight ? newWidth : newHeight;
                    toheight = towidth;
                    if (ow > oh)
                    {
                        toheight =Convert.ToInt32(double.Parse(oh.ToString())/double.Parse(ow.ToString())*towidth);
                    }
                    else
                    {
                        towidth = Convert.ToInt32(double.Parse(ow.ToString()) / double.Parse(oh.ToString()) * toheight);
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 在图片上生成文字水印
        /// </summary>
        /// <param name="filePath">原服务器图片路径</param>
        /// <param name="savePath">生成的带水印的图片路径</param>
        /// <param name="addText">水印文字 </param>
        /// <param name="wordFont">水印字体 eg:System.Drawing.Font("Verdana", 16)</param>
        /// <param name="wordColor">水印颜色 eg:System.Drawing.Color.Blue</param>
        /// <param name="x">水印位置：左上角X坐标</param>
        /// <param name="y">水印位置：左上角Y坐标</param>
        public static void AddWaterMarkWord(string filePath, string savePath, string addText, Font wordFont, Color wordColor, int x, int y)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(wordColor);

            g.DrawString(addText, wordFont, b, x,y);
            g.Dispose();

            image.Save(savePath);
            image.Dispose();
        }

        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="filePath">原服务器图片路径</param>
        /// <param name="savePath">生成的带图片水印的图片路径</param>
        /// <param name="watherMarkPath">水印图片路径</param>
        /// <param name="x">水印位置：左上角X坐标</param>
        /// <param name="y">水印位置：左上角Y坐标</param>
        public static void AddWaterMarkPic(string filePath, string savePath, string watherMarkPath, int x, int y)
        {
            System.Drawing.Image oImage = System.Drawing.Image.FromFile(filePath);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(watherMarkPath);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(oImage);
            g.DrawImage(copyImage, new System.Drawing.Rectangle(oImage.Width - copyImage.Width, oImage.Height - copyImage.Height, copyImage.Width, copyImage.Height),x, y, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

            oImage.Save(savePath);
            oImage.Dispose();
        }           
    }
}
